<template>
    <div class="relative size-full flex items-center justify-center overflow-hidden">

        <NCard class="relative z-4 w-auto rd-12px">
            <div class="w-400px lt-sm:w-300px">
                <header class="flex-y-center justify-between">
                    <h3 class="text-28px text-primary text-center font-500 lt-sm:text-22px">CoinPay 管理系统</h3>
                </header>
                <main class="pt-24px">
                    <div class="pt-24px">
                        <NForm ref="formRef" :model="model" :rules="rules" size="large" :show-label="false">
                            <NFormItem path="mobileNumber">
                                <NInput v-model:value="model.mobileNumber" placeholder="请输入手机号" />
                            </NFormItem>
                            <NFormItem path="password">
                                <NInput
                                    v-model:value="model.password"
                                    type="password"
                                    show-password-on="click"
                                    placeholder="请输入密码"
                                />
                            </NFormItem>
                            <NSpace vertical :size="24">
                                <NButton
                                    type="primary"
                                    size="large"
                                    round
                                    block
                                    :loading="loading"
                                    @click="onLoginClick"
                                >
                                    确定
                                </NButton>
                            </NSpace>
                        </NForm>
                    </div>
                </main>
            </div>
        </NCard>


        <div
            class="g-recaptcha"
            ref="recaptchaRef"
            :data-sitekey="siteKey"
            data-size="invisible"
            data-callback="onCaptchaVerified"
        ></div>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useMessage } from 'naive-ui'
import { login, verifyRecaptcha } from '@/api/user'
import { actions } from '@/store/app'
import type { FormInst, FormRules } from 'naive-ui'

const message = useMessage()
const router = useRouter()
const formRef = ref<FormInst | null>(null)
const loading = ref<boolean>(false)

const model = reactive<Api.Auth.LoginPrarams>({
    mobileNumber: '',
    password: ''
})


interface GoogleRecaptchaResult {
    success: boolean
    challenge_ts?: string
    hostname?: string
    score?: number
    action?: string
}
interface GoogleCaptchaWindow extends Window {
    grecaptcha: any
}

const siteKey = '6Ldo8IUrAAAAAOsqe19xn4au-gZ-yzR00BP9yOWP'

function onLoginClick() {
    const grecaptcha = (window as GoogleCaptchaWindow).grecaptcha
    if (grecaptcha && recaptchaRef.value) {
        grecaptcha.execute()
    } else {
        console.warn('grecaptcha 尚未加载完成')
    }
}

const rules: FormRules = {
    mobileNumber: {
        required: true,
        message: '请输入手机号'
    },

    password: {
        required: true,
        message: '请输入密码'
    }
}
// 验证成功的回调方法（由 Google 回调执行）
;(window as any).onCaptchaVerified = function (token: string) {
    console.log('验证码通过，token:', token)
    handleSubmit(token)
}


function handleSubmit(token: string) {
    if (!googleModel.captchaToken) {
        alert('请先完成验证码')
        return
    }

    verifyRecaptcha({
        token: token
    }).then(res => {
        debugger
        if (res.success) {
            // formRef.value?.validate(async errors => {
            //     if (!errors) {
            //
            //         const [err, res] = await login(model)
            //         if (!err) {
            //             const { token, userInfo } = res!
            //
            //             actions.setToken(token)
            //             actions.setUserInfo(userInfo)
            //             router.push('/user/list')
            //             message.success('登录成功，欢迎回来')
            //         }
            //     }
            // })
        } else {
            alert('验证失败')
        }
    })

}
</script>
